<template>
  <el-dialog
    :title="title"
    :visible="visible"
    width="60%"
    :modal="false"
    :before-close="closeForm"
    :close-on-click-modal="false"
  >
    <el-form ref="empPostEdit" :model="empPost" :rules="rules">
      <el-form-item label="任职公司" prop="CompanyId">
        <companySelect
          v-model="empPost.CompanyId"
          :parent-id="comId"
          placeholder="选择任职公司"
        />
      </el-form-item>
      <el-form-item label="任职部门" prop="DeptId">
        <deptSelect
          v-model="empPost.DeptId"
          :company-id="empPost.CompanyId"
          :status="[1]"
          :is-chiose-unit="false"
          placeholder="选择任职部门"
        />
      </el-form-item>
      <el-form-item label="岗位" prop="PostCode">
        <treeDicItem
          v-model="empPost.PostCode"
          :dic-id="HrItemDic.post"
          placeholder="岗位"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { add } from '@/api/emp/empPost'
import deptSelect from '@/components/unit/deptSelect.vue'
import companySelect from '@/components/company/companySelect.vue'
import { HrItemDic } from '@/config/publicDic'
export default {
  name: 'AddEmpPost',
  components: {
    deptSelect,
    companySelect
  },
  props: {
    empId: {
      type: String,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      HrItemDic,
      title: '新增岗位',
      empPost: {},
      rules: {
        DeptId: [
          {
            required: true,
            message: '任职部门不能为空！',
            trigger: 'blur'
          }
        ],
        CompanyId: [
          {
            required: true,
            message: '任职公司不能为空！',
            trigger: 'blur'
          }
        ],
        PostCode: [
          { required: true, message: '岗位不能为空!', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    comId() {
      return this.$store.getters.curComId
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  methods: {
    reset() {
      this.empPost = {
        CompanyId: this.comId
      }
    },
    save() {
      const that = this
      this.$refs['empPostEdit'].validate((valid) => {
        if (valid) {
          that.add()
        } else {
          return false
        }
      })
    },
    async add() {
      this.empPost.EmpId = this.empId
      await add(this.empPost)
      this.$message({
        message: '添加成功!',
        type: 'success'
      })
      this.$emit('close', true)
    },
    closeForm() {
      this.$emit('close', false)
    },
    resetForm() {
      this.empPost = {
        CompanyId: this.comId
      }
    }
  }
}
</script>
